package org.study.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.study.base.utils.BaseResult;
import org.study.base.utils.ResponseUtil;
import org.study.security.entity.LoginUser;
import org.study.security.entity.User;
import org.study.security.utils.TokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @program: securityparent
 * @description: 认证过滤器
 * @author: lishuang
 * @create: 2021-12-03 16:58
 **/
@Component
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private TokenUtil tokenUtil;
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(TokenUtil tokenUtil,RedisTemplate redisTemplate,AuthenticationManager authenticationManager){
        this.authenticationManager = authenticationManager;
        this.tokenUtil = tokenUtil;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/login","POST"));
    }

    /**
     * 获取表单用户名密码
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            return this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 认证成功
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        LoginUser principal = (LoginUser) authResult.getPrincipal();
        // 生成token
        String token = this.tokenUtil.generateToken(principal.getCurrentUserInfo().getUsername());

        /***
         * 把用户名称和用户权限列表放到redis
         */
        this.redisTemplate.opsForValue().set(principal.getCurrentUserInfo().getUsername(),token);
        ResponseUtil.out(response, BaseResult.ok().data("token",token));
    }

    /**
     * 认证失败
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.out(response, BaseResult.error());
    }
}
